from app_base import *
from app_element import *
from settings import *
from web_element import *
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import StaleElementReferenceException
import random,sys
    

def cycle_click(app, item, _id, page_type):
    if page_type == "WebPage":
        interval = 0
        view = app.views()[item]
    elif page_type == "VideoObject":
        interval = 1.5
        view = app.video_views()[item]

    logger.debug("缓存{}view元素".format(page_type))
    looks = xhs_tab_share.find_one({'_id': _id}, {'looks': 1})["looks"]
    cycles = int(min(looks, CYCLES_LIMIT))  # 限制单个任务单次最多循环次数
    logger.info("从数据库查询任务，任务(looks)总计{}，循环(cycles)总计{}".format(looks, cycles))

    for cycle in range(1, cycles, 1):

        if looks > 0 or looks is None == False:
            logger.debug("点击进入第{}个文章内页".format(item + 1))

            try:
                view.click()
                logger.debug("成功进入缓存的view元素")
            except StaleElementReferenceException as msg:
                app.get_screenshot_as_file()
                logger.error("StaleElementReferenceException：{}：没有找到缓存的view元素".format(msg))
                time.sleep(1)
                logger.debug("等{}秒".format())
                try:
                    view.click()
                    logger.debug("重试，成功进入缓存的view元素")
                except StaleElementReferenceException as msg:
                    app.get_screenshot_as_file()
                    logger.error("StaleElementReferenceException：{}：没有找到缓存的view元素".format(msg))
                    app.back(interval=0.1)
                    logger.debug("可能是回退失败，再次尝试按返回键")
                    view.click()
                    logger.debug("成功进入缓存的view元素")

            logger.debug("正常进入第{}个文章内页".format(item + 1))

            xhs_tab_share.update_one({'_id': _id}, {'$inc': {'looked': 1, 'looks': -1}})
            logger.debug("记录已完成次数上传到数据库")

            looks = xhs_tab_share.find_one({'_id': _id}, {'looks': 1})["looks"]
            logger.info("从数据库查询任务，当前任务(looks)剩余总计{}，当前循环(cycles)计数{}".format(looks, cycle))

            app.back(interval=interval)
            logger.debug("回退列表视图")

        else:
            logger.info("当前任务已完成，连续回退至主页")
            break

    app.back(num=3, interval=0.5)  # 循环完成后连按返回3次回到app主页面
    logger.info("顺利完成一组循环，连续回退至主页")


def cycle_swipe(app, work, swipe_count=SWIPE_COUNT):
    _id = work['_id']
    page_type = work['@type']

    headline = work['headline']
    content = work['content']
    if headline == "" or content == "" :
        video_content = "".join([headline, content])
    else:
        video_content = " ".join([headline, content])
    logger.debug("任务标题:{}".format(video_content))

    while swipe_count > 0:
        item = 0
        app.swipe_x(0.9, 0.33, 2000)  # 下滑约半屏
        # time.sleep(0.5)
        # app.swipe_x(0.73, 0.4, 1500)  # 下滑约半屏
        logger.info("下滑文章列表")
        if page_type == "WebPage":
            logger.debug("页面类型:{}".format(page_type))
            views = app.views()  # 视图内的列表
            while item < len(views):  # 遍历视图内的文章列表
                logger.info('点击屏幕中的第{}/{}个文章'.format(item + 1, len(views)))
                views[item].click()  # 点击进入内页
                # is_img = app.is_img()
                # if is_img is True:  # 尝试寻找图文类型的返回按钮
                if True:
                    time.sleep(1)
                    app.swipe_x(0.7, 0.4, 1000)  # 找到就是图文类型，下滑小半屏幕
                    logger.debug("任务标题:{}".format(headline))
                    h1_text = app.h1_text()
                    logger.debug("页面标题:{}".format(h1_text))
                    if h1_text == headline:  # 如果是分享链接的标题，就找到了需要的文章
                        logger.info('成功找到对应文章:{}'.format(h1_text))
                        app.back()  # 点击返回按钮回到信息流页面
                        cycle_click(app, item, _id, page_type="WebPage")  # 调用循环点击
                        logger.info('------------------🎉🎉顺利完成一组任务🎉🎉----------------------')
                        return
                    else:
                        app.back()
                        logger.debug("标题不匹配，回退列表视图向下寻找")

                else:
                    app.back()  # 若是非图文的视频类型点击回退到视图列表
                    logger.debug("非图文的视频类型点击回退到视图列表")
                time.sleep(0.5)  # 等一下加载
                logger.debug("等待元素列表视图加载")
                item += 1
            swipe_count -= 1
            logger.info('下滑倒计数{}'.format(swipe_count))

        elif page_type == "VideoObject":
            logger.debug("页面类型:{}".format(page_type))
            video_views = app.video_views()  # 视图内的视频列表
            while item < len(video_views):  # 遍历视图内的文章列表
                logger.info('点击屏幕中的第{}/{}个文章'.format(item + 1, len(video_views)))
                video_views[item].click()  # 点击进入内页
                video_text = str(app.vedio_h1_text())
                logger.info("页面标题:{}\n\t\t\t\t\t\t\t\t\t任务标题:{}".format(video_text[:25],video_content[:25]))
                if video_text[:25] == video_content[:25]:  # 如果是分享链接的标题，就找到了需要的文章
                    logger.info('{}找到对应文章:{}'.format(video_text[:25] == video_content[:25],video_text))
                    app.back()  # 点击返回按钮回到信息流页面
                    cycle_click(app, item, _id, page_type="VideoObject")  # 调用循环点击
                    logger.info('------------------🎉🎉顺利完成一组任务🎉🎉----------------------')
                    return
                else:
                    app.back()
                    logger.debug("标题不匹配，回退列表视图向下寻找")
                time.sleep(0.5)  # 等一下加载
                logger.debug("等待元素列表视图加载")
                item += 1
            swipe_count -= 1
            logger.info('下滑倒计数{}'.format(swipe_count))

    logger.info('查询超时，前10屏都未能找到元素，请确认文章是否存在，或手动下拉至所需的文章附近')
    # app.quit()


def work_analysis(limit=10):
    works = xhs_tab_share.find({'looks': {'$gte': TASK_FILTER}, "using_lock": False}).limit(limit)  # 查询一组待办任务，筛选太小的任务被丢弃
    n = random.randint(0, works.count() - 1)
    work = works[n]  # 随机获取其中的一条
    logger.info(work)
    web_info = share_link_analysis(work['share_link'])
    work.update(web_info)
    xhs_tab_share.update_one({'_id': work['_id']}, {'$set': work})
    return work


def work_start(desired_capabilities, DRIVER_SERVER, try_count=TRY_COUNT):
    while try_count > 0:
        try:
            logger.debug("尝试建立服务器和终端的链接👎")
            app = PoHome(desired_capabilities, DRIVER_SERVER)
            logger.info("成功建立服务器和终端的链接👌")
            while True:
                work = work_analysis()  # 查询合适的任务
                # time.sleep(5)
                # app.bottom_search(work['red_id'])  # 点击搜索用户名关键字
                app.bottom_search_angela()
                time.sleep(VEIW_WAIT)  # 暂停几秒，有必要的话手动拖到对应位置
                cycle_swipe(app, work, swipe_count=40)
        except ValueError as msg:
            app.quit()
            logger.error('ValueError:{}数据库中已无待办任务,退出进程'.format(msg))
            return None
        except UnboundLocalError as msg:
            # app.quit()
            logger.error('UnboundLocalError:{}可能是设备没有链接上'.format(msg))
        except TimeoutException as msg:
            app.get_screenshot_as_file()
            logger.error('TimeoutException:{}查找元素超时，可能是网络异常,尝试重启任务'.format(msg))
        except:
            app.get_screenshot_as_file()
            logger.error('其他类型的异常:{}，尝试重启任务'.format(sys.exc_info()))
        finally:
            try_count -= 1
            logger.info("剩余重试次数{}".format(try_count))
    logger.info("结束进程\n-------")


def main():
    print("请运行任务调度模块")
    # work_start(desired_capabilities=VIVO,DRIVER_SERVER='http://192.168.3.15:4723/wd/hub')


if __name__ == '__main__':
    main()